//
//  Forum_List_detali_Controller.m
//  Pacific_Computer
//
//  Created by 范琦 on 14-12-17.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "Forum_List_detali_Controller.h"
#import "Forum_detail_List.h"
#import "ForumCell.h"
#import "UIImageView+WebCache.h"
#import "UIScrollView+MJRefresh.h"
#import "UIScrollView+Extension.h"
#import "UIColor+AddColor.h"
#import "ForumNoCell.h"
#import "Forum_detail_ViewController.h"
#import "NetHandler.h"

@interface Forum_List_detali_Controller ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UIView *view1;
@property (nonatomic, retain) UIView *view2;
@property (nonatomic, retain) UIView *view3;
@property (nonatomic, retain) UISegmentedControl *seg;
@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) NSMutableArray *arr;



@end

@implementation Forum_List_detali_Controller
- (void)dealloc
{
    [_view1 release];
    [_view2 release];
    [_view3 release];
    [_seg release];
    [_table release];
    [_arr release];
    [_bHot release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.seg = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"最新回复", @"最近发表", @"精华帖", nil]];
    self.seg.selectedSegmentIndex = 0;
    self.seg.frame = CGRectMake(5, 64, self.view.bounds.size.width - 10, self.view.bounds.size.height / 18);
    [self.view addSubview:self.seg];
    [_seg release];
    
    self.view1 = [[UIView alloc]initWithFrame:CGRectMake(5, self.seg.frame.origin.y + self.seg.bounds.size.height, self.seg.bounds.size.width, self.view.bounds.size.height * 7 / 9)];
    self.view1.backgroundColor = [UIColor huiseColor];
    [self.view addSubview:self.view1];
    [_view1 release];
    
    self.view2 = [[UIView alloc]initWithFrame:CGRectMake(5, self.seg.frame.origin.y + self.seg.bounds.size.height, self.seg.bounds.size.width, self.view.bounds.size.height * 7 / 9)];
    self.view2.backgroundColor = [UIColor huiseColor];
    [self.view addSubview:self.view2];
    [_view2 release];
    
    self.view3 = [[UIView alloc]initWithFrame:CGRectMake(5, self.seg.frame.origin.y + self.seg.bounds.size.height, self.seg.bounds.size.width, self.view.bounds.size.height * 7 / 9)];
    self.view3.backgroundColor = [UIColor huiseColor];
    [self.view addSubview:self.view3];
    [_view3 release];
    
    [self.seg addTarget:self action:@selector(change:) forControlEvents:UIControlEventValueChanged];
    [self changeVC:self.seg.selectedSegmentIndex];
    
    

    self.table = [[UITableView alloc]initWithFrame:CGRectMake(5, 0, self.view1.bounds.size.width - 10, self.view1.bounds.size.height)];
    self.table.backgroundColor = [UIColor whiteColor];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view1 addSubview:self.table];
    [_table release];

    
    
    [self setupRefresh];
    
    
    
    
}

// 最新回复网络请求=============
- (void)view1Handles
{
    self.arr = [NSMutableArray array];
    NSString *str = [[NSString stringWithFormat:@"http://mrobot.pconline.com.cn/v3/itbbs/newForums/%@?orderby=replyat&pageNo=1&pageSize=20", self.bHot.forumId] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
    request.HTTPMethod = @"GET";
    [self.arr removeAllObjects];
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *arr = [result objectForKey:@"topicList"];
        for (NSDictionary *dic in arr) {
            Forum_detail_List *list = [[Forum_detail_List alloc]init];
            [list setValuesForKeysWithDictionary:dic];
            
            NSString *str1 = [list.image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [NetHandler getDataWithUrl:str1 completion:^(NSData *data) {
                UIImage *image = [UIImage imageWithData:data];
                list.imagee = image;
            }];
            [self.arr addObject:list];
            [list release];
        }
        [self.table reloadData];
 
    }];
}

// 最近发表网络请求==============
- (void)view1Handles1
{
    self.arr = [NSMutableArray array];
    NSString *str = [[NSString stringWithFormat:@"http://mrobot.pconline.com.cn/v3/itbbs/newForums/%@?orderby=postat&pageNo=1&pageSize=20", self.bHot.forumId] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self.arr removeAllObjects];
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *arr = [result objectForKey:@"topicList"];
        for (NSDictionary *dic in arr) {
            Forum_detail_List *list = [[Forum_detail_List alloc]init];
            [list setValuesForKeysWithDictionary:dic];
            NSString *str1 = [list.image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [NetHandler getDataWithUrl:str1 completion:^(NSData *data) {
                UIImage *image = [UIImage imageWithData:data];
                list.imagee = image;
            }];
            [self.arr addObject:list];
            [list release];
        }
        [self.table reloadData];
    }];

}
- (void)view1Handles2
{
    self.arr = [NSMutableArray array];
    NSString *str = [[NSString stringWithFormat:@"http://mrobot.pconline.com.cn/v3/itbbs/newForums/%@?pageNo=1&filter=pick&pageSize=20", self.bHot.forumId] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
    request.HTTPMethod = @"GET";
    [self.arr removeAllObjects];
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *arr = [result objectForKey:@"topicList"];
        for (NSDictionary *dic in arr) {
            Forum_detail_List *list = [[Forum_detail_List alloc]init];
            [list setValuesForKeysWithDictionary:dic];
            
            NSString *str1 = [list.image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [NetHandler getDataWithUrl:str1 completion:^(NSData *data) {
                UIImage *image = [UIImage imageWithData:data];
                list.imagee = image;
            }];
            [self.arr addObject:list];
            [list release];
        }
        [self.table reloadData];
 
    }];
    
}
- (void)setupRefresh
{
    //    NSLog(@"进入了setupRefresh");
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    
    [self.table addHeaderWithTarget:self action:@selector(headerRereshing)];
    //进入刷新状态(一进入程序就下拉刷新)
    [self.table headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.table addFooterWithTarget:self action:@selector(footerRereshing)];
}



#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    
    //1. 在这调用请求网络数据方法（刷新数据）
    if (self.seg.selectedSegmentIndex == 0) {
        
        [self view1Handles];
    }else if (self.seg.selectedSegmentIndex == 1){
        [self view1Handles1];
    }else if (self.seg.selectedSegmentIndex == 2){
        [self view1Handles2];
    }
    
    
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.table reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.table headerEndRefreshing];
    });
}

//   进入加载状态
- (void)footerRereshing
{
    //1. 拼接口等操作
    
    
    // 请求加载数据
    if (self.seg.selectedSegmentIndex == 0) {
        NSString *str = [[NSString stringWithFormat:@"http://mrobot.pconline.com.cn/v3/itbbs/newForums/%@?orderby=replyat&pageNo=%lu&pageSize=20", self.bHot.forumId, self.arr.count + 1] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
        request.HTTPMethod = @"GET";
        [NetHandler getDataWithUrl:str completion:^(NSData *data) {
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *arr = [result objectForKey:@"topicList"];
            for (NSDictionary *dic in arr) {
                Forum_detail_List *list = [[Forum_detail_List alloc]init];
                [list setValuesForKeysWithDictionary:dic];
                NSString *str1 = [list.image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [NetHandler getDataWithUrl:str1 completion:^(NSData *data) {
                    UIImage *image = [UIImage imageWithData:data];
                    list.imagee = image;
                }];
                [self.arr addObject:list];
                [list release];
            }
            [self.table reloadData];
 
        }];

    }else if (self.seg.selectedSegmentIndex == 1){
        NSString *str = [[NSString stringWithFormat:@"http://mrobot.pconline.com.cn/v3/itbbs/newForums/%@?orderby=postat&pageNo=%lu&pageSize=20", self.bHot.forumId, self.arr.count / 20 + 1] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [NetHandler getDataWithUrl:str completion:^(NSData *data) {
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *arr = [result objectForKey:@"topicList"];
            for (NSDictionary *dic in arr) {
                Forum_detail_List *list = [[Forum_detail_List alloc]init];
                [list setValuesForKeysWithDictionary:dic];
                
                NSString *str1 = [list.image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [NetHandler getDataWithUrl:str1 completion:^(NSData *data) {
                    UIImage *image = [UIImage imageWithData:data];
                    list.imagee = image;
                }];
                [self.arr addObject:list];
                [list release];
            }
            [self.table reloadData];
        }];
    }else if (self.seg.selectedSegmentIndex == 2){
        NSString *str = [[NSString stringWithFormat:@"http://mrobot.pconline.com.cn/v3/itbbs/newForums/%@?pageNo=%lu&filter=pick&pageSize=20", self.bHot.forumId, self.arr.count / 20 + 1] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [NetHandler getDataWithUrl:str completion:^(NSData *data) {
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *arr = [result objectForKey:@"topicList"];
            for (NSDictionary *dic in arr) {
                Forum_detail_List *list = [[Forum_detail_List alloc]init];
                [list setValuesForKeysWithDictionary:dic];
                
                NSString *str1 = [list.image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [NetHandler getDataWithUrl:str1 completion:^(NSData *data) {
                    UIImage *image = [UIImage imageWithData:data];
                    list.imagee = image;
                }];
                [self.arr addObject:list];
                [list release];
            }
            [self.table reloadData];
        }];

    }
    
    
    
    
    
    
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.table reloadData];
        [self.table footerEndRefreshing];
    });
}




- (void)change:(UISegmentedControl *)seg
{
    [self changeVC:seg.selectedSegmentIndex];
}


- (void)changeVC:(NSInteger)seg
{
    if (seg == 0) {
        for (UIView *view in [self.table subviews]) {
            [view removeFromSuperview];
        }
        self.table = [[UITableView alloc]initWithFrame:CGRectMake(5, 0, self.view1.bounds.size.width - 10, self.view1.bounds.size.height)];
        self.table.backgroundColor = [UIColor whiteColor];
        self.table.delegate = self;
        self.table.dataSource = self;
        [self.view1 addSubview:self.table];
        [_table release];
        [self.view bringSubviewToFront:self.view1];
        [self.table removeFromSuperview];
        [self.view1 addSubview:self.table];
        [self setupRefresh];
    }
    else if (seg == 1){
        for (UIView *view in [self.table subviews]) {
            [view removeFromSuperview];
        }
        self.table = [[UITableView alloc]initWithFrame:CGRectMake(5, 0, self.view1.bounds.size.width - 10, self.view1.bounds.size.height)];
        self.table.backgroundColor = [UIColor whiteColor];
        self.table.delegate = self;
        self.table.dataSource = self;
        [self.view1 addSubview:self.table];
        [_table release];
        [self.view bringSubviewToFront:self.view2];
        [self.table removeFromSuperview];
        [self.view2 addSubview:self.table];
        [self setupRefresh];
        
        
    }
    else if (seg == 2){
        for (UIView *view in [self.table subviews]) {
            [view removeFromSuperview];
        }
        self.table = [[UITableView alloc]initWithFrame:CGRectMake(5, 0, self.view1.bounds.size.width - 10, self.view1.bounds.size.height)];
        self.table.backgroundColor = [UIColor whiteColor];
        self.table.delegate = self;
        self.table.dataSource = self;
        [self.view1 addSubview:self.table];
        [_table release];
        [self.view bringSubviewToFront:self.view3];
        [self.table removeFromSuperview];
        [self.view3 addSubview:self.table];
        [self setupRefresh];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.arr.count == 0) {
        return 0;
    }else{
        return self.arr.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Forum_detail_List *list = [self.arr objectAtIndex:indexPath.row];
    
    
    NSDate *nowDate = [NSDate date];
    NSTimeInterval time = [nowDate timeIntervalSince1970];
    long a = [list.createAt longValue];
    NSTimeInterval cha = time - a / 1000;
    
    NSDate *allDate = [NSDate dateWithTimeIntervalSinceNow:-cha];
    
    NSDateFormatter *format = [[NSDateFormatter alloc]init];
    [format setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr = [format stringFromDate:allDate];
    
    
    
    if (list.image.length != 0) {
        ForumCell *cell = [tableView dequeueReusableCellWithIdentifier:@"a"];
        if (cell == nil) {
            cell = [[[ForumCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"a"] autorelease];
        }
        

        cell.title.text = list.title;
        cell.message.text = list.message;
        cell.imageV.image = list.imagee;
        NSString *str = [NSString stringWithFormat:@"%@阅/%@楼", list.floor, list.view];
        cell.floor.text = str;
        
        if (cha < 60) {
            cell.date.text = [NSString stringWithFormat:@"%.0f秒前", cha];
        }else if (cha < 60 * 60){
            cell.date.text = [NSString stringWithFormat:@"%.0f分钟前", cha / 60];
        }else if (cha < 60 * 60 * 24){
            cell.date.text = [NSString stringWithFormat:@"%.0f小时前", cha / 60 / 60];
        }else if (cha >= 60 * 60 * 24){
            cell.date.text = dateStr;
        }
        
        
        
        return cell;
    }else{
         ForumNoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"b"];
        if (cell == nil) {
            cell = [[[ForumNoCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"b"] autorelease];
        }
        
        cell.title.text = list.title;
        cell.messge.text = list.message;
        if (cha < 60) {
            cell.date.text = [NSString stringWithFormat:@"%.0f秒前", cha];
        }else if (cha < 60 * 60){
            cell.date.text = [NSString stringWithFormat:@"%.0f分钟前", cha / 60];
        }else if (cha < 60 * 60 * 24){
            cell.date.text = [NSString stringWithFormat:@"%.0f小时前", cha / 60 / 60];
        }else if (cha >= 60 * 60 * 24){
            cell.date.text = dateStr;
        }
        
        return cell;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    Forum_detail_ViewController *detail = [[Forum_detail_ViewController alloc]init];
    Forum_detail_List *list = [self.arr objectAtIndex:indexPath.row];
    detail.list = list;
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];


}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Forum_detail_List *list = [self.arr objectAtIndex:indexPath.row];
    if (list.image.length == 0) {
        return 150;
    }
    else{
        return 300;
    }


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
